package hiatao.puzzle.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import haitao.puzzle.R;
import hiatao.puzzle.utils.BitmapSaveUtils;
import hiatao.puzzle.utils.FileUtils;
import hiatao.puzzle.utils.StatusBarCompat;
import hiatao.puzzle.widget.CropImageView;

public class ImageCutActivity  extends Activity implements OnClickListener{

	private ImageView img;
    private View top_back;
    private View save;
    private String  url;
    CropImageView mCropImage;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_crop_image);
		findView();
		init();
		StatusBarCompat.compat(this, getResources().getColor(R.color.primary));
	}

	private void init() {
		url =getIntent().getStringExtra("URL");
		top_back.setOnClickListener(this);
		save.setOnClickListener(this);
		mCropImage=(CropImageView)findViewById(R.id.cropImg);
		ImageLoader.getInstance().loadImage(url, new SimpleImageLoadingListener()
        {
				public void onLoadingComplete(String imageUri, android.view.View view, final android.graphics.Bitmap loadedImage) {
            	runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mCropImage.setDrawable(new BitmapDrawable(loadedImage),250,250);
					}
				});
            	};
        	}
        );
	}

	private void findView() {
        img = (ImageView) findViewById(R.id.img);
        top_back =  findViewById(R.id.top_back);
        save =  findViewById(R.id.save);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.top_back:
			finish();
			break;
		case R.id.save:
			save();
			break;

		default:
			break;
		}
	}
	private void save(){
		new Thread(new Runnable(){

			@Override
			public void run() {
				String filename = FileUtils.createFileNmae(".jpg");
				BitmapSaveUtils.saveBmpToSd(FileUtils.getAppPath(),mCropImage.getCropImage(),filename,100,true);
				Intent intent = new Intent();
				intent.setClass(ImageCutActivity.this, PhotoProcessActivity.class);
				intent.putExtra("URL","file:///"+FileUtils.getAppPath()+filename);
				startActivity(intent);
				finish();
			}
		}).start();
	}
}
